public class Test02 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int sumNumbers(TreeNode root) {
        //函数头
        //根节点前驱和为0
        return dfs(root, 0);
    }

    //函数体
    private int dfs(TreeNode root, int prevSum) {
        //计算根节点的位置的数
        prevSum = prevSum * 10 + root.val;
        if (root.left == null && root.right == null) {
            return prevSum;
        }
        //处理左子树
        int leftSum = 0;
        if (root.left != null){
            leftSum = dfs(root.left, prevSum);
        }
        //处理右子树
        int rightSum = 0;
        if (root.right != null){
            rightSum = dfs(root.right, prevSum);
        }
        return leftSum + rightSum;
    }

    public static void main(String[] args) {

    }
}
